import type { Repository } from "@lix-js/client"
import type { CliStep } from "../../utils"
import type { NextJSProject } from "../scan-next-project"
import type { RoutingStrategy } from "./promptRoutingStrategy"
import path from "node:path"

export const createI18nFile: CliStep<
	{
		repo: Repository
		nextProject: NextJSProject
		routingStrategy: RoutingStrategy
	},
	unknown
> = async (ctx) => {
	const i18nFilePath = path.join(
		ctx.nextProject.srcRoot,
		ctx.nextProject.typescript ? "lib/i18n.ts" : "lib/i18n.js"
	)

	const TypescriptTemplate = `// file generated by the Paraglide-Next init command
import { PrefixStrategy, Navigation, Middleware } from "@inlang/paraglide-next"
import type { AvailableLanguageTag } from "@/paraglide/runtime"

const strategy = ${
		ctx.routingStrategy.type === "cookie"
			? `DetectionStrategy<AvailableLanguageTag>()`
			: ctx.routingStrategy.type === "domain"
			? `DomainStrategy<AvailableLanguageTag>({ domains: ${JSON.stringify(
					ctx.routingStrategy.domains
			  )} })`
			: `PrefixStrategy<AvailableLanguageTag>({ prefixDefault: "never" })`
	};

export const middleware = Middleware({ strategy });
export const { Link, useRouter, usePathname, redirect, permanentRedirect } = Navigation({ strategy });
`

	const JavascriptTemplate = `// file generated by the Paraglide-Next init command
import { PrefixStrategy, Navigation, Middleware } from "@inlang/paraglide-next"

/** 
 * @type {import("@inlang/paraglide-next").${
		{ prefix: "PrefixStrategy", cookie: "DetectionStrategy", domain: "DomainStrategy" }[
			ctx.routingStrategy.type
		]
 }<
 *     import("@/paraglide/runtime").AvailableLanguageTag
 * >} 
 */
const strategy = ${
		ctx.routingStrategy.type === "cookie"
			? `DetectionStrategy()`
			: ctx.routingStrategy.type === "domain"
			? `DomainStrategy({ domains: ${JSON.stringify(ctx.routingStrategy.domains)} })`
			: `PrefixStrategy({ prefixDefault: "never" })`
	};

export const middleware = Middleware({ strategy });
export const { Link, useRouter, usePathname, redirect, permanentRedirect } = Navigation({ strategy });
`

	const file = ctx.nextProject.typescript ? TypescriptTemplate : JavascriptTemplate

	//create the folder if it doesn't exist
	await ctx.repo.nodeishFs.mkdir(path.dirname(i18nFilePath), { recursive: true })
	await ctx.repo.nodeishFs.writeFile(i18nFilePath, file)
	return ctx
}
